package com.yx.filesystem.client;

import java.math.BigInteger;
import com.yx.filesystem.storage.Archive;
import com.yx.filesystem.storage.SocketClient;
import com.yx.filesystem.storage.State;

public class ServerNode {
	private String id;
	private String ip;
	private int port;
	private boolean alive = false;
	private long lastAliveTime = 0;
	private State state = new State();

	protected ServerNode(String ip, int port) {
		this.ip = ip;
		this.port = port;
	}

	public String getId() {
		return id;
	}

	public String getIp() {
		return ip;
	}
	protected boolean hasFile(Archive file){
		if(!state.getFileState().containsKey(file.getNodeId()[0])){
			return false;
		}
		BigInteger maxFileNumber=state.getFileState().get(file.getNodeId()[0]);
		if(maxFileNumber.compareTo(file.getFileTotalNumber())>=0){
			return true;
		}
		return false;
	}
	public State getState() {
		return state;
	}
	public int getPort() {
		return port;
	}

	public boolean isAlive() {
		return alive;		
	}

	protected void setAlive(boolean alive) {
		this.alive = alive;		
		lastAliveTime = System.currentTimeMillis();		
	}
	protected long howLong(){
		return  System.currentTimeMillis() - lastAliveTime;
	}

	protected boolean heartbeat() {		
		SocketClient client = new SocketClient();
		try {
			if (client.open(ip, port)) {				
				state = client.getStorageState(null);
				if(state!=null&&state.getServerId()!=null){
					this.id=state.getServerId();
				}
				setAlive(true);
			} else {
				setAlive(false);
			}
			return isAlive();
		} catch (Throwable e) {
			//e.printStackTrace();
			setAlive(false);
			return isAlive();
		} finally {
			client.close();
		}
	}
}
